<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-button type="success" @click="showAdd">添加角色</el-button>
      <el-table :data="roleList" border>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  class="'vcenter'"
                  @close="removeById(scope.row, item1.id)"
                  closable
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[
                    'bdbottom',
                    'vcenter',
                    i2 === 0 ? 'bdtop' : '',
                    'vcenter',
                  ]"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      @close="removeById(scope.row, item2.id)"
                      closable
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      :class="['bdbottom', i3 === 0 ? 'bdtop' : '']"
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      @close="removeById(scope.row, item3.id)"
                      closable
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <pre></pre>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色介绍" prop="roleDesc"></el-table-column>
        <el-table-column>
          <template slot-scope="scope">
            <el-button type="success" @click="showEditRole(scope.row.id)"
              >编辑</el-button
            >
            <el-button type="danger" @click="delRole(scope.row.id)"
              >删除</el-button
            >
            <el-button type="warning" @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
        <!-- <el-table-column label="地址" prop="path"></el-table-column> -->
      </el-table>

      <!-- 新建角色对话框 -->
      <el-dialog
        title="新建角色"
        :visible.sync="showAddDialogVisible"
        @closed="addDialogVisibleClosed('add')"
      >
        <el-form
          :model="addForm"
          :rules="editFormRules"
          ref="addFormRef"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色介绍" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisibleClosed('add')">取 消</el-button>
          <el-button type="primary" @click="addRole">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 修改角色对话框 -->
      <el-dialog
        title="修改角色"
        :visible.sync="editDialogVisible"
        @closed="addDialogVisibleClosed('edit')"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色介绍" prop="roleDesc">
            <el-input v-model="editForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisibleClosed('edit')">取 消</el-button>
          <el-button type="primary" @click="editRole">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 分配权限 -->
      <el-dialog
        title="分配权限"
        :visible.sync="showSetRightDialogVisible"
        @closed="addDialogVisibleClosed('t')"
      >
        <el-tree
          ref="treeRef"
          :data="rightsLsit"
          :props="treeProps"
          :default-checked-keys="defKeys"
          show-checkbox
          node-key="id"
          default-expand-all
        >
        </el-tree>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisibleClosed('t')">取 消</el-button>
          <el-button type="primary" @click="allotRights">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleId: "",
      roleList: {},
      roles: {},
      showAddDialogVisible: false,
      editDialogVisible: false,
      showSetRightDialogVisible: false,
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      editForm: {
        roleName: "",
        roleDesc: "",
      },
      rightsLsit: {},
      // 树形控件数据类型绑定对象
      treeProps: {
        children: "children",
        label: "authName",
      },
      // 默认选中的节点数组值
      defKeys: [],
      editFormRules: {
        roleName: [
          {
            required: true,
            message: "请输入角色名",
            trigger: "blur",
          },
        ],
      },
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get("roles")
      if (res.meta.status !== 200)
        return this.$message.error("获取角色列表失败")
      this.roleList = res.data
      // console.log(this.roleList)
    },
    // 显示编辑角色对话框
    async showEditRole(id) {
      const { data: res } = await this.$http.get("roles/" + id)

      if (res.meta.status !== 200) return this.$message.error("角色获取失败")
      this.editForm = res.data
      this.editDialogVisible = true
    },
    async editRole() {
      const { data: res } = await this.$http.put(
        "roles/" + this.editForm.roleId,
        this.editForm
      )
      if (res.meta.status !== 200) return this.$message.error("角色修改失败")
      this.editForm = ""
      this.editDialogVisible = true
      return this.$message.success("修改成功")
    },
    delRole(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showCancelButton: true,
        cancelButtonClass: "cancel",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(`roles/${id}`)
          if (res.meta.status !== 200) return this.$message.error("删除失败")
          this.getRoleList()
          this.$message({
            type: "success",
            message: "删除成功!",
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          })
        })
    },
    addDialogVisibleClosed(type) {
      if (type === "edit") this.editDialogVisible = false
      if (type === "t") this.showSetRightDialogVisible = false
      if(type==='add') this.showAddDialogVisible=false
    },
    removeById(role, rightId) {
      this.$confirm("此操作将删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showCancelButton: true,
        cancelButtonClass: "cancel",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200) return this.$message.error("删除失败")
          //   this.getRoleList()
          role.children = res.data
          this.$message({
            type: "success",
            message: "删除成功!",
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          })
        })
    },
    async showSetRightDialog(role) {
      this.defKeys = []
      this.roleId = role.id
      const { data: res } = await this.$http.get("rights/tree")
      if (res.meta.status !== 200) return this.$message.error("获取权限失败")
      this.rightsLsit = res.data
      console.log(this.rightsLsit)
      this.getLeafKeys(role, this.defKeys)
      this.showSetRightDialogVisible = true
    },
    // 通过递归方式来获取三级权限节点
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr)
      })
    },
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const keyStr = keys.join(",")
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: keyStr }
      )
      if (res.meta.status !== 200) return this.$message.error("分配权限失败")

      this.$message.success("分配成功")
      this.showSetRightDialogVisible = false
      this.getRoleList()
    },
    showAdd(){
      this.showAddDialogVisible=true
    },
    addRole(){
      this.$refs.addFormRef.validate(async value =>{
        if(!value) return
          const {data : res} = await this.$http.post('/roles', this.addForm)
          if(res.meta.status!==201) return this.$message.error('添加失败')
          this.showAddDialogVisible=false
          this.getRoleList()
          return this.$message.success(res.meta.msg)
      })
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
</style>